package com.auto.qinglong.net.client

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.auto.base.net.ResultWrapper
import com.auto.base.util.GsonUtil
import com.auto.qinglong.net.client.beans.Task
import com.auto.qinglong.net.client.beans.TaskGroupTagBean
import com.auto.qinglong.net.client.beans.toTask

class TaskPagingSource(
    private val repository: QlRepository,
    val search: String,
    val bean: TaskGroupTagBean? = null
) : PagingSource<Int, Task>() {
    override fun getRefreshKey(state: PagingState<Int, Task>): Int? {
        // 1. 当前屏幕中正在可见的 item 的 position
        val anchorPosition = state.anchorPosition ?: return null

        // 2. 找到这个位置最近的一页
        val anchorPage = state.closestPageToPosition(anchorPosition)

        // 3. 尝试返回这页的下一页或上一页页码作为刷新起点
        return anchorPage?.prevKey?.plus(1)
            ?: anchorPage?.nextKey?.minus(1)
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Task> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
            Log.d("=========", "触发了getTask")
            val result = repository.getTask(search, page, pageSize, bean)
            Log.d("=========", GsonUtil.toJson(result))
            when (result) {
                is ResultWrapper.Success -> {
                    val items = result.data?.data?.map {
                        it.toTask()
                    } ?: arrayListOf()
                    LoadResult.Page(
                        data = items,
                        prevKey = if (page == 1) null else page - 1,
                        nextKey = if (result.data?.data.isNullOrEmpty()) null else page + 1
                    )
                }

                is ResultWrapper.Error -> {
                    Log.d("=========", "result.exception${result.exception.message}")
                    LoadResult.Error(result.exception)
                }
            }
        } catch (e: Exception) {
            Log.d("=========", "result.exception${e.message}")
            LoadResult.Error(e)
        }
    }
}